package com.kaifamiao.month05.day10;

import lombok.Data;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Data
public class Server {

    private static Set<Socket> clientSet = new HashSet<>();

    public static Set<Socket> getClientSet() {
        return clientSet;
    }

    private static final int CAPACITY = 3;

    public static void main(String[] args) throws IOException {

        ServerSocket server = new ServerSocket(9999);
        System.out.println("服务已经启动……");
        /*
         * 发消息的线程池
         * 接收消息的线程池
         */
//        ThreadPoolExecutor sendPool = new ThreadPoolExecutor(CAPACITY, CAPACITY, 10L, TimeUnit.SECONDS,new SynchronousQueue<>());
        ThreadPoolExecutor receivePool = new ThreadPoolExecutor(CAPACITY, CAPACITY, 10L, TimeUnit.SECONDS, new SynchronousQueue<>());
        do {
            Socket request = server.accept();
            clientSet.add(request);
            receivePool.execute(new ClientRunnable(request));
//            sendPool.execute(new ClientRunnable(request));
        } while (clientSet.size() != CAPACITY);
        System.out.println("服务器结束");
    }
}

@Data
class ClientRunnable implements Runnable {

    private Socket socket;  // 每个线程对应相应的socket对象
    private static Set<String> messages = new HashSet<>();

    public ClientRunnable(Socket socket) {
        this.socket = socket;
    }

    /**
     * 实现对客户端的请求的响应
     */
    @Override
    public void run() {
        try {
            if (!socket.isOutputShutdown()) { // 客户端发送了消息
                byte[] bytes = socket.getInputStream().readAllBytes(); // 获取到客户端的输入
                // 将当前客户端的内容发送到其他客户端
                // 解析从客户端获取的内容
                byte[] bs = Arrays.copyOf(bytes, 36);
                String name = new String(bs); // 当前客户端的名称
                byte[] messageBytes = new byte[bytes.length - bs.length];
                System.arraycopy(bytes, bs.length, messageBytes, 0, messageBytes.length);
                String mes = new String(messageBytes); // 客户端输入的内容
                System.out.println("服务器接收到信息：" + mes); // 输出客户端输入的内容
                String message = name + ":" + mes;
                messages.add(message);
                socket.getOutputStream().write("消息发送成功！".getBytes(StandardCharsets.UTF_8));
                socket.shutdownOutput();
            } else {
                for (String s : messages) {
                    socket.getOutputStream().write(s.getBytes(StandardCharsets.UTF_8));
                }
                socket.shutdownOutput();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
